﻿using System;
using System.Collections.Generic;
using System.IO;
using Xom.Generator;

namespace XomXSD
{
    class Program
    {
        // /namespace:
        private static string _nameSpace;
        // /outputdir:
        private static DirectoryInfo _outputDir = null;

        private static IList<string> _xsdFiles; 

        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(@"PLEASE USE PARAMETERS! EXAMPLE: /namespace:Test /outputdir:C:\Test test.xsd");
            }

            System.Reflection.Assembly ass = System.Reflection.Assembly.GetExecutingAssembly();
            DirectoryInfo localDir = new DirectoryInfo(ass.Location.Replace("XomXSD.exe", ""));
            if (!localDir.Exists)
            {
                Console.WriteLine("ERROR ### CAN'T READ LOCAL DIRECTORY OF XOMXSD.EXE! ###");
                Console.ReadLine();
            }

            _xsdFiles = new List<string>();

            foreach (string parameter in args)
            {
                if (parameter.ToLower().StartsWith(@"/namespace:"))
                {
                    string value = parameter.Replace("/namespace:", "");
                    value = value.Replace(" ", "");
                    _nameSpace = value;
                }
                else if (parameter.ToLower().StartsWith(@"/outputdir:"))
                {
                    string value = parameter.Replace("/outputdir:", "");
                    value = value.Replace(" ", "");
                    _outputDir = new DirectoryInfo(value);
                }
                else
                {
                    string value = parameter.Replace(" ", "");
                    _xsdFiles.Add(value);
                }
            }

            //no outputDir specified
            if (_outputDir == null) _outputDir = localDir;
            if (string.IsNullOrEmpty(_nameSpace)) _nameSpace = "XomXSD";


            IList<string> checkedFiles = new List<string>();
            foreach (string file in _xsdFiles)
            {
                string fileName = file;

                if (!File.Exists(fileName))
                {
                    //fallback -> search in local directory
                    fileName = Path.Combine(localDir.FullName, fileName);
                    if (!File.Exists(fileName))
                    {
                        Console.WriteLine("ERROR ### CAN'T FIND XSD FILE '" + file + "'! ###");
                        continue;
                    }
                }

                checkedFiles.Add(fileName);
            }

            //start generat
            if (checkedFiles.Count > 0)
            {
                BindingGenerator.Load(checkedFiles, _nameSpace, _outputDir.FullName);
                Console.WriteLine("DONE!");
            }

            Console.ReadLine();
        }
    }
}
